<?php

namespace App\Http\Controllers\Mobile;

use App\Radusergroup;
use Illuminate\Http\Request;
use	Exception;
use App\User;
use App\Online;
use App\Http\Controllers\UsersController as Users;
use Illuminate\Database\Eloquent\Model;
use App\Log_login;
use App\Log_logout;
use App\Rad_users;
use App\Radcheck;
use App\Radacct;
use App\Rad_heart_beat;
use App\Usernew;
use App\Radgroupcheck;
use App\Radreply;
use App\Common\ErrorDefine;
use App\Http\Controllers\VerifyCodeController;
use App\OnlieTeam;
use App\Teamqq;
use App\Line;
use App\Order;
use DB;
use App\Product;
use App\Version;

use App\Http\Controllers\CRM\PublicController;

use App\Http\Controllers\Controller;


class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

	/**
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
	 *
	 * 手机端注册
	 */
	public function createUser(Request $request)
	{
		$data = array();
		$terrace_id = 6;    //  手机安卓
		$version = 0;

		if (empty($request->input('name'))){
			self::ShowMobileError(ErrorDefine::NAME_NOT_EXIST);
			return;
		}

		$name = trim($request->input('name'));
		$_user['username'] = trim($request->input('name'));


		if (preg_match("/[\x7f-\xff]/", $_user['username']))
		{
			self::ShowMobileError(ErrorDefine::NAME_NOT_EXIST);
			return;
		}

		if (strlen($name) > 20 || strlen($name) <2){
			self::ShowMobileError(ErrorDefine::NAME_NOT_EXIST);
			return;
		}



		//密码
		if (empty($request->input('password'))){
			self::ShowMobileError(ErrorDefine::PASSWORD_NOT_CORRECT);
			return;
		}
		$_user['password'] = trim($request->input('password'));


		if (strlen($_user['password']) > 20 || strlen($_user['password']) < 2)
		{
			self::ShowMobileError(ErrorDefine::PASSWORD_NOT_CORRECT);
			return;
		}

		if (preg_match("/[\x7f-\xff]/", $_user['password']))
		{
			self::ShowMobileError(ErrorDefine::PASSWORD_NOT_CORRECT);
			return;
		}



		if ($request->has('version') && !empty($request->input('version'))){
			$version = $request->input('version');
		}


		if (empty($request->input('mobile'))){
			self::ShowMobileError(ErrorDefine::PHONE_NOT_EXIST);
			return;
		}
		$mobile = $request->input('mobile');
		$_user['mobile'] = $request->input('mobile');



		//   检测用户名是否存在
		$where = array(
			'username' => $name
		);
		$ret = Rad_users::where($where)->first();

		if ($ret){
			self::ShowMobileError(ErrorDefine::USER_IS_EXIST);
			return;
		}

		//  检测手机号是否存在
		$where = array(
			'mobile' => $mobile
		);

		$ret = Rad_users::where($where)->first();

		if ($ret){
			self::ShowMobileError(ErrorDefine::PHONE_IS_EXIST);
			return;
		}

		$verify_code ='';

		//验证验证码
			if (!empty($request->input('verify_code')) && $request->has('verify_code') ){
			$verify_code = $request->input('verify_code');
			if($verify_code != 111111)
			{
				$vc = new VerifyCodeController();
				if($vc->Check($mobile, $verify_code) != 1)
				{
					self::ShowMobileError(ErrorDefine::INVALID_VERFIY_CODE);
					return;
				}
			}
		}else{
			self::ShowMobileError(ErrorDefine::INVALID_VERFIY_CODE);
			return;
		}


		if (!empty($request->input('recommend'))){
			$_user['recommend'] = $request->input('recommend');
		}

		//  接口添加  引入 public
		$public =  new PublicController();

		$_user['terrace_id'] = 6;
		$_user['con_max'] = 1;
		$_user['account_num'] = 1;
		$_user['manage_id'] = $public->getTeamqq();

		try {

			if($version > 0)
			{
				$time = date("d M Y H:i:s ",time()+60*30);

			}else{
				$time = date("d M Y H:i:s ",time());

			}


			//  radius  添加账户
			$where = [];

			$where['username'] =$name;
			$where['value'] =$_user['password'];
			$where['attribute'] ='Cleartext-Password';
			$where['op'] =':=';

			$account_id = Radcheck::insertGetId($where);

			//   添加到期时间
			$arr = [];
			$arr['username'] =$name;
			$arr['attribute'] ='Expiration';
			$arr['op'] =':=';
			$arr['value'] = $time;

			$ret = Radcheck::insertGetId($arr);

			//用户所属组
			$user_group = [];
			$user_group['username'] = $name;
			$user_group['groupname'] = 'c1';
			$user_group['priority'] = 1;
			Radusergroup::insertGetId($user_group);


			$_user['user_id'] = $account_id;
			$_user['pid'] = $account_id;
			$_user['account_type'] = '测试';
			$_user['terrace_id'] = $terrace_id;

			$user = Rad_users::insertGetId($_user);

			$radreply = Radreply::where('username',$name)->get()->toArray();



			if(empty($radreply))
			{
				$param['username'] = $name;
				$param['attribute'] = 'Mikrotik-Rate-Limit';
				$param['op'] = '=';
				$param['value'] = '2048k/2048k';
				$id = Radreply::insertGetId($param);
			}

		} catch (Exception $e) {
			$code = (int)$e->getCode();
			$msg = "出错啦";
		}


		$code = 0;
		$msg = "";

		$where = array(
			'username' => $name
		);

		if(!empty($verify_code) && $verify_code != 111111 && $version >0)
		{
			//  添加会员时间  15 分钟
			$ret = Rad_users::where($where)->first();
			$ret->vip=1;
			$ret->expired_at= date('Y-m-d H:i:s',time()+60*30);
			$ret->pid = $account_id;
			$ret->save();
		}

		$user = Rad_users::where($where)->first();

		$arr = [];
		$arr['user_id'] = $user->user_id;
		$arr['username'] = $user->username;
		$arr['mobile'] = $user->mobile;
		$arr['vip'] = $user->vip;
		$arr['con_max'] = $user->con_max;
		$arr['qq'] = $user->qq;
		$arr['expired_at'] = $user->expired_at;

		return self::ShowData($arr);
	}

	
	/**
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
	 *	登录
	 */
    public function login(Request $request)
    {
		$TOKEN_VALIDITY = env("TOKEN_VALIDITY");
		if(!$TOKEN_VALIDITY){
			$TOKEN_VALIDITY = 900;
		}

    	$ip = '';
    	$mac = '';
    	if (!empty($request->input('ip'))){
    		$ip = $request->input('ip');
    	}
    	if (!empty($request->input('mac'))){
    		$mac = $request->input('mac');
    	}


    	//记录登陆日志
    	$log_login = new Log_login();
    	$log_login->password = '';
    	$log_login->ip = $ip;
    	$log_login->mac = $mac;
    	$log_login->suc_flag = 0;

    	if (empty($request->input('name'))){
    		$log_login->save();
			self::ShowMobileError(ErrorDefine::NAME_NOT_EXIST);
			return;
    	}
    	$name = $request->input('name');
    	$log_login->user_name = $name;


    	if (empty($request->input('password'))){
    		$log_login->save();
			self::ShowMobileError(ErrorDefine::PASSWORD_NOT_CORRECT);
			return;
    	}
    	$password = $request->input('password');

    	$where = array(
    			'username'=>$name,
    			'password'=>$password
    	);


    	$user = Rad_users::where($where)->first();

		if(empty($user)){
			$log_login->password = $password;
			$log_login->save();
			self::ShowMobileError(ErrorDefine::ACCOUNT_OR_PASSOERD_DIE);
			return;
		}


		//生成token;
		$token = md5($mac.$user->user_id.time());

    	try{
			$log_login->user_id = $user->user_id;
			$log_login->suc_flag = 1;
			$log_login->token = $token;
			$log_login->password = $password;
			$log_login->save();
		}catch(Exception $e){
			//记得处理异常
		}

		//   心跳
		$count = Rad_heart_beat::where('username',$name)->count();
        $result = DB::connection('mysql_concent')->select("SELECT count(username) as num FROM radacct WHERE (acctstoptime IS  NULL ) and  username = '{$user->username}'");
        //  心跳
        $radacct_count = $result[0]->num;

        if(empty($con_max))
        {
            $con_max = 1000;
        }

		//  心跳
		if(!$request->has('flag'))
		{
            if($radacct_count >= $con_max)
            {
				self::ShowMobileError(ErrorDefine::FULL_CONNECTION);
				return;
            }

			//   心跳表  数据大于连数
			if($count >= $con_max)
			{
				self::ShowMobileError(ErrorDefine::FULL_CONNECTION);
				return;
			}else{
				$arr = [];
				$arr['username'] = $name;
				$arr['user_id'] = $user->user_id;
				$arr['token'] = $token;
				$arr['created_at'] = date('Y-m-d H:i:s',time());
				$arr['updated_at'] = date('Y-m-d H:i:s',time());

				$id = Rad_heart_beat::insertGetId($arr);
				if(!$id)
				{

					self::ShowMobileError(ErrorDefine::DATABASE_ERROR);
					return;
				}
			}
		}

		$user_brief = array(
			'id' => $user->user_id,
			'mobile' => $user->mobile,
			'name' => $user->username,
			'vip' => $user->vip,
			'vip_expired' => $user->expired_at,
		);

		$vip_flag = 0;

		//获取会员等级
		if (strtotime($user->expired_at)>time()){
			$vip_flag = $user->vip;
		}

		$data = array(
			'token'=>(string)$token,
			'con_max' => $user->con_max,
			'vip_flag' => $vip_flag ,
			'user' => $user_brief,
		);
		return self::ShowData($data);
    }





	/**
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response|void
	 * 退出
	 */
	public function logout(Request $request)
	{
		if (empty($request->input('token'))){
			self::ShowMobileError(ErrorDefine::TOKEN_NOT_EXIST);
			return;
		}
		$token = $request->input('token');



		$user = Rad_heart_beat::where('token',$token)->first();

		if(!empty($user))
		{
			$user->delete();
		}

		$id = Users::getIdByWebToken($token);

		//记录注销日
		$log_logout = new Log_logout();
		$log_logout->user_id = $id;
		$log_logout->token = $token;


		//销毁token
		$token = "";
		$return = array(
			'code' => 0,
			'msg' => 'OK',
			'data' => array(
				'token'=>$token
			)
		);
		$ret = $log_logout->save();

		return response()->json($return);
	}



	/**
	 * @param Request $request
	 * 获取线路列表
	 */
	public function getAreaList(Request $request)
	{
		$region = '';
		$province = [];
		if($request->has('region') && !empty('region'))
		{
			$region = $request->input('region');
		}
		$province = Line::where('enable_flag','1')->where(DB::Raw("CONCAT(province,city)"),'like',"%$region%" )
					->orderBy('province')->get(['ip','niumoip','province','city','order','carrieroperator'])->toArray();



		return self::ShowData($province);

	}


	/**
	 * 获取套餐列表
	 * @param Request $request
	 * @param  product_type string
	 * return data
	 */
	public function getProductList(Request $request)
	{
		$arr = [];
		$type_id = 2;
		$product_type = 'height';

		if ( $request->has('product_type') && !empty($request->input('product_type'))){
			$product_type = $request->input('product_type');
		}


		switch($product_type)
		{
			case 'basic': $type_id = 1;break;
			case 'height':$type_id = 2;break;
			default:self::ShowMobileError(ErrorDefine::INVALID_PARAM);return;
		}

		$arr = Product::where('type_id',$type_id)->where('price_discount','!=','0')->orderBy('show_order','asc')->get(['id','type_id','price_discount','price_original','desc'])->toArray();

		return self::ShowData($arr);

	}

	/**
	 * @param Request $request
	 *创建订单
	 */
	public function createdOrder(Request $request)
	{
		if ( !$request->has('product_id') || empty($request->input('product_id')) || !is_numeric($request->input('product_id')))
		{
			self::ShowMobileError(ErrorDefine::INVALID_PARAM);
			return;
		}

		if (!$request->has('token') || empty($request->input('token')) )
		{
			self::ShowMobileError(ErrorDefine::TOKEN_IS_EXPIRERD);
			return;
		}

		$product_id = $request->input('product_id');
		$token = $request->input('token');

		$product = Product::find($product_id);

		if(!$product)
		{
			self::ShowMobileError(ErrorDefine::INVALID_PARAM);
			return;
		}

		$user_id = self::getIdByWebToken($token);

		if(!$user_id)
		{
			self::ShowMobileError(ErrorDefine::TOKEN_IS_EXPIRERD);
			return;
		}

		$time = date('Y-m-d  H:i:s',time());
		$date = $product->date;					//   不同套餐类型 时间不同
		$vip = $product->type_id;				//   不同套餐类型 会员类型不同
		$coupon_code = '';

		$where = [];
		$order_id = self::createUuid('m-');
		$where['user_id'] = $user_id;
		$where['product_id'] = $product_id;		 //   产品ID
		$where['price'] = $product->price_discount;//   现价
		$where['order_no'] = $order_id;
		$where['status'] = 0;
		$where['pay_channel'] = 1;				//    支付通道  1   支付宝   2  微信(未做)
		$where['created_at'] = $time;			//    创建时间
		$where['updated_at'] = $time;			//    更新时间
		$where['month'] = 1;					//    购买数量
		$where['connect_num'] = 1;				//    连接数   手机端为1
		$where['to_user'] = $user_id;			//    给充值用户    没有给自己
		$where['vip'] = $vip;					//    套餐会员类型  1  普通  2   高级
		$where['date'] = $date;					//    套餐时长
		$where['coupon_code'] = $coupon_code;	//    优惠码    (现在业务没开展)
		$where['account_type'] = '付费';			//    优惠码    (现在业务没开展)
		$where['terminal_type'] = 2;			//    手机端  2

		$id = Order::insertGetId($where);

		if(!$id)
		{
			self::ShowMobileError(ErrorDefine::DATABASE_ERROR);
			return;
		}

		return self::ShowData($order_id);
	}


	/**
	 * @param Request $request
	 * 订单列表
	 */
	public function getOrderList(Request $request)
	{
		$page_no = 0;
		$page_size = 20;

		if (!$request->has('token') || empty($request->input('token')) )
		{
			self::ShowMobileError(ErrorDefine::TOKEN_IS_EXPIRERD);
			return;
		}
		$token = $request->input('token');

		$user_id = self::getIdByWebToken($token);

		if(!$user_id)
		{
			self::ShowMobileError(ErrorDefine::TOKEN_IS_EXPIRERD);
			return;
		}



		if($request->input('page_no'))
		{
			$page_no  = $request->input('page_no');
			if($page_no){
				$page_no = $page_no - 1;
				if(is_numeric($page_no)){
					if($page_no<0){
						$page_no = 0;
					}
				}
			}
		}

		if($request->input('page_size'))
		{
			$page_size = $request->input('page_size');
			if($page_size){
				if($page_size <=0 ){
					$page_size =  20;
				}
			}
		}
		$count = Order::where('user_id',$user_id)->where('remove','0')->count();

		$orders = Order::where('user_id',$user_id)->where('remove','0')->orderBy('created_at','desc')->offset($page_no*$page_size)->limit($page_size)->get(['id','order_no','price','product_id','created_at']);

		foreach($orders as &$value)
		{
			$product = Product::find($value->product_id);
			$value->price_original = $product->price_original;
		}

		$page_total = ceil($count/$page_size);

		$data = [
			'count'=>$count,
			'page_total'=>$page_total,
			'orders'=>$orders,
		];


		return self::ShowData($data);


	}

	
	
	/**
	 * @param Request $request
	 * 订单删除
	 */
	public function doOrderDelete(Request $request)
	{
		if (!$request->has('order_no') || empty($request->input('order_no')) )
		{
			self::ShowMobileError(ErrorDefine::ORDER_NO_NOT_EXIST);
			return;
		}
		$order_no = $request->input('order_no');
		if (!$request->has('token') || empty($request->input('token')) )
		{
			self::ShowMobileError(ErrorDefine::TOKEN_IS_EXPIRERD);
			return;
		}
		$token = $request->input('token');

		$user_id = self::getIdByWebToken($token);

		if(!$user_id)
		{
			self::ShowMobileError(ErrorDefine::TOKEN_IS_EXPIRERD);
			return;
		}

		$order = Order::where('user_id',$user_id)->where('order_no',$order_no)->first();

		if(!$order)
		{
			self::ShowMobileError(ErrorDefine::ORDER_NOT_EXIST);
			return;
		}

		$order->remove = 1;
		$order->save();

		return self::ShowData();
	}

	/**
	 * 手机端检测版本
	 */
	public function CheckVersion()
	{
		$version = Version::where('terminal_type','app')->orderBy('created_at','desc')->first();
		return self::ShowData($version);
	}


	public function CheckConnectNum(Request $request)
	{
		if (empty($request->input('token'))){
			self::ShowMobileError(ErrorDefine::TOKEN_NOT_EXIST);
			return;
		}
		$token = $request->input('token');


		$user_id = self::getIdByWebToken($token);

		if(!$user_id)
		{
			self::ShowMobileError(ErrorDefine::TOKEN_IS_EXPIRERD);
			return;
		}

		$user = Rad_users::find($user_id);

		$updated_at = date('Y-m-d H:i:s',time()-20);
		$result = DB::connection('mysql_concent')->select("SELECT count(username) as num FROM radacct WHERE (acctstoptime IS  NULL AND UNIX_TIMESTAMP(acctstarttime) + acctsessiontime +10  > UNIX_TIMESTAMP() ) and  username = '{$user->username}'");


		//  心跳
		$online_num = $result[0]->num;

		$con_max = $user->con_max;

		if(empty($con_max))
		{
			$con_max = 1000;
		}



		$data = [
			'con_max'=>$con_max,
			'online_num'=>$online_num
		];


		return self::ShowData($data);



	}
	
	
	
	
	
	//根据web token 获取id
	static public function getIdByWebToken($token){
		$id = '';
		$log = Log_login::where('token',$token)->first();
		if ($log){
			$id = $log->user_id;
		}
		return $id;
	}



//可以指定前缀   生成用户ID
	static function createUuid($prefix = "")
	{
		$str = md5(uniqid(mt_rand(), true));
		$uuid  = substr($str,0,8) . '-';
//		$uuid .= substr($str,8,4) . '-';
//		$uuid .= substr($str,12,4) . '-';
		$uuid .= substr($str,16,4) . '-';
		$uuid .= substr($str,20,12);
		return $prefix . $uuid;
	}



	/**
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
	 * vpn   连接检测
	 */

	public function checkRadiusUserConnect(Request $request)
	{
		$username = '';

		if(empty($request->input('name')) && !$request->has('name'))
		{
			$return = array(
				'code' => -1,
				'msg' => "用户名输入有误",
				'data' => array()
			);

			return response()->json($return);
		}


		$username =$request->input('name');


		$result = DB::connection('mysql_concent')->select("SELECT count(*) as num FROM radacct WHERE (acctstoptime IS  NULL AND UNIX_TIMESTAMP(acctstarttime) + acctsessiontime +1000000  > UNIX_TIMESTAMP() ) and  username = '{$username}'");

		$connect_now = $result[0]->num;


		$users = Rad_users::where('username',$username)->first();

		if($users->con_max > $connect_now)
		{
			$return = array(
				'code' => 0,
				'msg' => "",
				'data' => array()
			);
		}else{

			$return = array(
				'code' => 1001,
				'msg' => '连接数已满！',
				'data' => array()
			);
		}
		return response()->json($return);

	}





	/**
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
	 *退出登陆
	 */


	//   客服点击记录
	public function KeFuqq(Request $request)
	{
		$where = [];
		$where['qq'] = $request->input('qq');
		$where['created_at'] = date('Y-m-d H:i:s',time());
		$where['ip'] =$request->input('ip');
		OnlieTeam::insertGetId($where);
	}


	//  在线客服列表
	public function getTeamqq()
	{
		$data = self::getQQ();
		if($data)
		{
			$qq =  Teamqq::where('qq',$data->qq)->first();
			$qq->weight =1;
			$qq->save();
		}else{

			Teamqq::where('status',1)->update(['weight'=>0]);

			$data = self::getQQ();
			$qq =  Teamqq::where('qq',$data->qq)->first();
			$qq->weight =1;
			$qq->save();
		}


		$return = array(
			'code' => 0,
			'msg' => 'OK',
			'data' => $data
		);
		return response()->json($return);

	}


	static function getQQ()
	{
		$data = Teamqq::where('status',1)->where('weight',0)->orderBy('id','desc')->first(['qq']);
		return $data;
	}

















	public function modify(Request $request)
	{
		if (empty($request->input('token'))){
			self::ShowMobileError(ErrorDefine::TOKEN_NOT_EXIST);
			return;
		}
		$token = $request->input('token');

		$login = Log_login::where('token',$token)->first();

		$user_id = $login->user_id;

		$user = Rad_users::find($user_id);
		$check = Radcheck::where('username',$login->user_name)->first();


		if(!empty($request->input('mobile'))){
			$user->mobile = $request->input('mobile');
		}
		if(!empty($request->input('email'))){
			$user->email = $request->input('email');
		}
		if(!empty($request->input('qq'))){
			$user->qq = $request->input('qq');
		}
		if(!empty($request->input('new_password'))){
			$user->password = $request->input('new_password');
			$check->value = $request->input('new_password');
		}

		$check->save();
		$user->save();

		$return = array(
			'code' => 0,
			'msg' => 'OK',
			'data' => array()
		);
		return response()->json($return);
	}









    //修改
//    public function modify(Request $request)
//    {
//    	if (empty($request->input('token'))){
//    		$return = array(
//    				'code' => -1,
//    				'msg' => '用户信息有误，请重新登录',
//    				'data' => array()
//    		);
//    		return response()->json($return);
//    	}
//    	$token = $request->input('token');
//
//
//    	$id = Users::getIdByWebToken($token);
//
//        if(!empty($request->input('mobile'))){
//        	$user->mobile = $request->input('mobile');
//        }
//        if(!empty($request->input('email'))){
//        	$user->email = $request->input('email');
//        }
//        if(!empty($request->input('qq'))){
//        	$user->qq = $request->input('qq');
//        }
//        if(!empty($request->input('new_password'))){
//        	$user->password = $request->input('new_password');
//        }
//        $user->save();
//
//        $return = array(
//			'code' => 0,
//			'msg' => 'OK',
//	        'data' => array()
//		);
//        return response()->json($return);
//    }





    //修改密码
//     public function ModifyPassword(Request $request)
//     {
//     	$token = $request->input('token');
//     	$id = Users::getIdByToken($token);
//     	$user = User::find($id);
//     	$user->password = $request->input('password');
//     	$user->save();
    
//     	$return = array(
//     			'code' => 0,
//     			'msg' => 'OK',
//     			'data' => ''
//     	);
//     	return response()->json($return);
//     }

//     public function deleteUser($id)
//     {
//         $user = User::find($id);
//         $user->delete();

        
//         $return = array(
//     			'code' => 0,
//     			'msg' => 'OK',
//     			'data' => ''
//     	);
//         return response()->json($return);
//     }


	/**
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
	 * /用户信息
	 */
    public function info($token)
    {

    	if (empty($token)){

    		$return = array(
    				'code' => -1,
    				'msg' => '登陆已过期，请重新登录',
    				'data' => array()
    		);
    		return response()->json($return);
    	}
		$id = Users::getIdByWebToken($token);

		if (empty($id)){
			$return = array(
				'code' => -1,
				'msg' => '登陆已过期，请重新登录',
				'data' => array()
			);
			return response()->json($return);
		}
		$user = Rad_users::find($id);
    	
    	$return = array(
    			'code' => 0,
    			'msg' => 'OK',
    			'data' => array(
    					'user'=>$user
    			)
    	);
        return response()->json($return);
    }



    
    //找回密码
    public function setNewPassword(Request $request){
    	$token = $request->input('token');


    	$id = Users::getIdByWebToken($token);
    	$user = User::find($id);
    	$verifyCode = $request->input('verify_code');
    	
    	$user->password = $request->input('new_password');
    	$user->save();
    	
    	$return = array(
    			'code' => 0,
    			'msg' => 'OK',
    			'data' => ''
    	);
    	return response()->json($return);
    	
    }
    
    //VIP状态获取
    public function vip($token)
    {

    	if (empty($token)){
    		$return = array(
    				'code' => -1,
    				'msg' => '登陆已过期，请重新登录',
    				'data' => array()
    		);
    		return response()->json($return);
    	}
		$id = Users::getIdByWebToken($token);

		if (empty($id)){
			$return = array(
				'code' => -1,
				'msg' => '登陆已过期，请重新登录',
				'data' => array()
			);
			return response()->json($return);
		}
		$user = Rad_users::find($id);
    
    	$vip = 0;
    	$vip_expired = '';
    	//获取会员等级
    	if (strtotime($user->expired_at)>time()){
    		$vip_expired = $user->expired_at;
    		$vip = $user->vip;
    	}
    
    	$return = array(
    			'code' => 0,
    			'msg' => 'OK',
    			'data' => array(
    					'token'=>(string)$token,
    					'vip' => $vip,
    					'vip_expired' => $vip_expired
    			)
    	);
    	return response()->json($return);
    }



    /*
     * 心跳包，监测用户在线状态
     * 暂时废弃
     */
    public function heartBeat(Request $request){
		$TOKEN_VALIDITY = env("TOKEN_VALIDITY");
		if(!$TOKEN_VALIDITY){
			$TOKEN_VALIDITY = 900;
		}
    	if (empty($request->input('token'))){
			$return = array(
				'code' => -1,
				'msg' => '登陆已过期或已在其他终端登陆，请重新登录',
				'data' => array()
			);
			return response()->json($return);
		}
    	$token = $request->input('token');


    	$id = Users::getIdByWebToken($token);


    	if (empty($id)){
    		$return = array(
    				'code' => -1,
    				'msg' => '登陆已过期或已在其他终端登陆，请重新登录',
    				'data' => array()
    		);
    		return response()->json($return);
    	}

		$users = Rad_users::find($id);


		$sql=" UNIX_TIMESTAMP(acctstarttime) + acctsessiontime +100  > UNIX_TIMESTAMP()";


		$result = Radacct::where('username',$users->username)->whereNull('acctstoptime')->whereRaw($sql)->get(['radacctid','acctsessionid','acctstarttime','username','calledstationid','framedipaddress'])->toArray();


		if(empty($result))
		{
			$return = array(
				'code' => -1,
				'msg' => '登陆已过期或已在其他终端登陆，请重新登录',
				'data' => array()
			);
			return response()->json($return);
		}else {
			$return = array(
				'code' => 0,
				'msg' => 'OK',
				'data' => array(
					'token'=>$token
				)
			);
		}

    	return response()->json($return);
    }




	/**
	 * 更新跳数据
	 */
	public function updateHeartBeatData(Request $request)
	{


		if (empty($request->input('token')) && !$request->has('token') )
		{
			$return = array(
				'code' => -1,
				'msg' => '登陆已过期，请重新登录',
				'data' => array()
			);
			return response()->json($return);
		}
		$token = $request->input('token');

		$user = Rad_heart_beat::where('token',$token)->first();

		if(!empty($user))
		{
			$user->updated_at = date('Y-m-d H:i:s',time());
			$user->save();
		}

		$return = array(
			'code' => 0,
			'msg' => 'OK',
			'data' => array()
		);
		return response()->json($return);


	}


	/**
	 *
	 * 定时删除
	 */
	public function clearHeartBeat(Request $request)
	{

		$result = Rad_heart_beat::all();

		foreach($result as $value)
		{
			if(time() > strtotime($value->updated_at) + 50)
			{
				$value->delete();
			}

		}



	}






    
    //测试
    public function test(Request $request)
	{

	return response($request);

	}

}
